package com.zc.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.zc.common.Result;
import com.zc.exception.CustomerException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author zc
 * @Date 2025/8/21
 * @apiNote
 */
@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.address}")
    private String ip;
    @Value("${server.port}")
    private String port;

    private static final String BASE_FILE_PATH = System.getProperty("user.dir") + "/files";
    //获取当前用户目录("user.dir")（即工程根目录）,并在其下创建files目录

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isBlank(originalFilename)) {
            return Result.error("文件上传失败");
        }
        //时间戳，当作标识
        long flag = System.currentTimeMillis();
        String fileName = flag + "_" + originalFilename;
        // 文件路径
        File finalFile = new File(BASE_FILE_PATH + "/" + fileName);
        if (!finalFile.getParentFile().exists()) {
            finalFile.getParentFile().mkdirs();
        }
        file.transferTo(finalFile);
        //返回的url
        String url = "http://" + ip + ":" + port + "/files/download?fileName=" + fileName;
        return Result.success(url);
    }

    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        File file = new File(BASE_FILE_PATH + "/" + fileName);
        if (!file.exists()) {
            throw new CustomerException("文件不存在");
        }
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Content-Disposition", "application; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        response.setContentType("application/octet-stream");
        FileUtil.writeToStream(file, outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
